#!/usr/bin/env python
# -*- coding:utf-8 -*-


'''
@CreateTime: 2020/12/10 15:09
@Author : shouke
'''

from components.decoraters.action_decorater import ActionDecorator

class Counter(object):
    @ActionDecorator.action_register('exec_counter', 'Counter', 'exec_counter', __name__)
    @classmethod
    def exec_counter(self, config:dict, *args, **kwargs):
        '''
        运行计数器
        :param config 配置信息，具体如下
        {
            "refName": "counter1", #要求计数器引用名称场景内唯一（ 不同链路中定义的计数器引用变量可以重复）
            "value": 1, #初始值
            "increment": 2, #增量步长值
            "maximum": 1000, #最大值
            "numberFormat": "100000", #暂时未实现
            "independently_each_user": False # 是否每个用户独立 True 每个用户拥有自己的独立计数器 False 所有用户共享一个计数器
        }
        '''
        user_share_resouce_dict = kwargs['user_share_resource_dict']
        user = kwargs['user']
        user_resource_dict = user.user_resource_dict[user.chain_id]

        if config['independently_each_user']:
            if config['refName'] not in user_resource_dict:
                user_resource_dict[config['refName']] = config['value']
            elif user_resource_dict[config['refName']] < config['maximum']:
                user_resource_dict[config['refName']] += min(config['increment'], config['maximum'] - user_resource_dict[config['refName']])
        else:
            if config['refName'] not in user_share_resouce_dict:
                user_share_resouce_dict[config['refName']] = config['value']
                user_resource_dict[config['refName']] = config['value']
            elif user_share_resouce_dict[config['refName']] < config['maximum']:
                user_share_resouce_dict[config['refName']] += min(config['increment'], config['maximum'] - user_share_resouce_dict[config['refName']])
                user_resource_dict[config['refName']] = user_share_resouce_dict[config['refName']]

